import httpUtil from "@/utils/HttpUtil";
import {Message} from "element-ui";
import {executeSelectApi} from "@/api/sqlExecuteApi";
import moment from 'moment';

let reg = /period=(\w+)/;
function getPeriodDate(period){
    // 3-时  2-日   1-月
    let timeType, beginDate, endDate;
    let date = new Date();
    switch(period) {
        case 'year':
            timeType = 1;
            beginDate = moment(date).startOf('year');
            endDate = moment(date).endOf('year');
            break;
        case 'lastYear':
            timeType = 1;
            beginDate = moment(date).subtract(1,'years').startOf('year');
            endDate = moment(date).subtract(1, 'years').endOf('year');
            break;
        case 'month':
            timeType = 2;
            beginDate = moment(date).startOf('month');
            endDate = moment(date).endOf('month');
            break;
        case 'lastMonth':
            timeType = 2;
            beginDate = moment(date).subtract(1, 'months').startOf('month');
            endDate = moment(date).subtract(1, 'months').endOf('month');
            break;
        case 'week':
            timeType = 2;
            beginDate = moment(date).startOf('week').add(1,' days');
            endDate = moment(date).endOf('week').add(1, 'days');
            break;
        case 'lastWeek':
            timeType = 2;
            beginDate = moment(date).subtract(1,'weeks').startOf('week').add(1,'days');
            endDate = moment(date).subtract(1,'weeks').endOf('week').add(1, 'days');
            break;
        case 'today':
            timeType = 3;
            beginDate = endDate = moment(date);
            break;
        case 'yesterday':
            timeType = 3;
            beginDate = endDate = moment(date).subtract(1,'days');
            break;
        default:
    }
    return { timeType, beginDate, endDate };
}
export async function getDataJson(cptDataForm, uuid, stores, storeUpdater ){
    let resStr = '{}';//防止JSON解析报错
    let iptStr = cptDataForm.dataText;
    if (cptDataForm.dataSource === 1){
        resStr = JSON.parse(iptStr);
    }else if(cptDataForm.dataSource === 2){//调接口
        iptStr = cptDataForm.apiUrl;
        if (iptStr){
            // 构建get请求的查询字符串
            let passStr = cptDataForm.passParams;
            let params = { companyId:144 };
            if ( passStr && passStr.length ) {
                let regRes = reg.exec(passStr);
                if ( regRes && regRes.length === 2 ) {
                    // 时间区间字段特殊处理
                    passStr = passStr.replace(reg, '');
                    let { timeType, beginDate, endDate } = getPeriodDate(regRes[1]);
                    passStr = passStr + '&timeType=' + timeType + '&beginDate=' + beginDate.format('YYYY-MM-DD') + '&endDate=' + endDate.format('YYYY-MM-DD');
                }
                let arr = passStr.split('&');
                arr.forEach(item=>{
                    let temp = item.split('=');
                    params[temp[0]] = temp[1];
                });                
            }
            await httpUtil.doRequest(iptStr,'get', params).then(res => {
                resStr = res.data ? res.data : res;  
                // 用组件uuid作为键名
                let obj = { ...stores, [uuid]:resStr };
                storeUpdater(obj);             
            })        
        }else{
            Message.error("接口地址不能为空");
        }
    }else if(cptDataForm.dataSource === 3){
        iptStr = cptDataForm.sql
        if (iptStr){
            let staticData = JSON.parse(cptDataForm.dataText);
            const isArray = Array.isArray(staticData);
            await executeSelectApi({sql:iptStr, isArray}).then(res => {
                resStr = res.data;
            })
        }else{
            Message.error("SQL不能为空");
        }
    }
    return resStr;
}

let cptTimer = {}

export function pollingRefresh(uuid, cptDataForm, loadData){
    if(uuid) {
        clearInterval(cptTimer[uuid]);//清除旧的定时器
    }
    if (!cptDataForm){
        Message.warning("cptDataForm==>null");
        return;
    }
    if (!loadData){
        Message.warning("子组件未实现数据解析方法");
        return;
    }
    loadData();
    if (cptDataForm.pollTime && cptDataForm.pollTime !== 0) {//轮询
        cptTimer[uuid] = setInterval(function () {
            loadData();
        }, cptDataForm.pollTime * 1000)
    }
}

export function clearCptInterval(uuid, clearAll){
    if(uuid) {
        clearInterval(cptTimer[uuid]);//清除旧的定时器
    }
    if (clearAll){
        for (const key in cptTimer) {
            clearInterval(cptTimer[key]);
        }
    }
}
